#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

#define MAX_PRODUCTS 1000
#define MAX_USERS 500
#define MAX_ORDERS 5000
#define MAX_NAME_LENGTH 50
#define MAX_ADDRESS_LENGTH 100
#define MAX_CATEGORY_LENGTH 30
#define RESTOCK_THRESHOLD 10
#define CLEANUP_DAYS 30
#define CATEGORY_DELIMITER '/'
#define DATA_FILE "ecommerce_data.dat"
#define PRODUCTS_PATH "D:\\c\\text\\products.csv"

typedef struct {
    int id;               // 商品ID
    char name[50];        // 商品名称
    char category[30];     // 分类路径(如'电子产品/手机')
    float price;          // 单价
    int stock;            // 当前库存
    int sales;            // 累计销量
} Product;

// 用户信息结构体
typedef struct {
    int id;
    char name[MAX_NAME_LENGTH];
    char address[MAX_ADDRESS_LENGTH];
    char contact[20];     // 联系方式
} User;

// 订单状态枚举
typedef enum {
    PENDING_PAYMENT,
    PAID,
    SHIPPED,
    COMPLETED
} OrderStatus;

// 订单信息结构体
typedef struct {
    int id;
    OrderStatus status;
    int user_id;
    int product_id;
    int quantity;
    time_t order_time;
} Order;

// 补货任务结构体
typedef struct {
    int product_id;
    int priority;  // 1-高优先级, 2-中优先级, 3-低优先级
    time_t timestamp;
} RestockTask;

// 商品类别树节点
typedef struct CategoryNode {
    char name[MAX_CATEGORY_LENGTH];
    struct CategoryNode *parent;
    struct CategoryNode *children[MAX_PRODUCTS];
    int child_count;
    int product_count;
    float sales_total;
} CategoryNode;

// 全局数据存储
Product products[MAX_PRODUCTS];
int product_count = 0;

User users[MAX_USERS];
int user_count = 0;

Order orders[MAX_ORDERS];
int order_count = 0;

RestockTask restock_queue[MAX_PRODUCTS];
int restock_count = 0;

// 栈结构用于订单状态变更历史
typedef struct {
    int order_id;
    OrderStatus old_status;
    time_t timestamp;
} OrderHistoryItem;

OrderHistoryItem order_history[MAX_ORDERS];
int history_count = 0;

// 哈希表结构用于用户信息快速查找
typedef struct HashNode {
    int key;
    User *user;
    struct HashNode *next;
} HashNode;

HashNode *user_hash_table[100];

// 全局类别树根节点
CategoryNode *category_root = NULL;

// 函数声明
void initialize_system();
void initialize_hash_table();
int add_product(int id, const char *name, const char *category, float price, int stock);
int find_product_by_id(int id);
int find_product_by_name(const char *name);
void sort_products_by_name();
void sort_products_by_sales();  // 新增：按销量排序
void print_product(int index);
int add_user(int id, const char *name, const char *address, const char *contact);
User* find_user_by_id(int id);
int find_user_by_name(const char *name);
void print_user(int index);
int create_order(int user_id, int product_id, int quantity);
int process_payment(int order_id);
int process_shipment(int order_id);
int confirm_receipt(int order_id);
Order* find_order_by_id(int id);
void sort_orders_by_time();
void print_order(int index);
int update_stock(int product_id, int quantity);
void check_low_stock();
void process_restock_tasks();
void push_order_history(int order_id, OrderStatus old_status);
OrderHistoryItem* get_order_history(int order_id, int *count);  // 修改：获取订单历史
int has_order_history(int order_id);
void enqueue_restock_task(int product_id, int priority);
RestockTask dequeue_restock_task();
int is_restock_queue_empty();
CategoryNode* create_category_node(const char *name);
CategoryNode* find_or_create_category_path(const char *path);  // 新增：创建类别路径
void add_child_category(CategoryNode *parent, CategoryNode *child);
void traverse_category_tree(CategoryNode *node, int depth);
void update_category_stats(Product *product, float sales_amount);
unsigned int hash_function(int key);
void hash_table_insert(int key, User *user);
User* hash_table_lookup(int key);
void print_system_status();
void cleanup_old_orders();
void show_menu();
void input_product();
void list_products();
void list_products_by_sales();  // 新增：按销量列出商品
void input_user();
void list_users();
void input_order();
void list_orders();
void search_product();
void search_user();
void search_order();
void wait_for_user();
void save_data_to_file();  // 新增：保存数据到文件
void load_products();
void build_category_tree();  // 新增：构建类别树
void print_category_stats();  // 新增：打印类别统计

// 主函数
int main() {
    load_products();
    initialize_system();
    
    int choice;
    do {
        show_menu();
        printf("请输入您的选择: ");
        if (scanf("%d", &choice) != 1) {
            printf("输入错误，请输入一个数字\n");
            while (getchar() != '\n'); // 清除错误输入
            continue;
        }
        getchar();  // 消耗换行符
        
        switch (choice) {
            case 1: input_product(); wait_for_user(); break;
            case 2: list_products(); wait_for_user(); break;
            case 3: search_product(); wait_for_user(); break;
            case 4: input_user(); wait_for_user(); break;
            case 5: list_users(); wait_for_user(); break;
            case 6: search_user(); wait_for_user(); break;
            case 7: input_order(); wait_for_user(); break;
            case 8: list_orders(); wait_for_user(); break;
            case 9: search_order(); wait_for_user(); break;
            case 10: 
                printf("请输入要处理付款的订单ID: ");
                int order_id;
                scanf("%d", &order_id);
                getchar();  // 消耗换行符
                process_payment(order_id);
                wait_for_user();
                break;
            case 11:
                printf("请输入要处理发货的订单ID: ");
                scanf("%d", &order_id);
                getchar();  // 消耗换行符
                process_shipment(order_id);
                wait_for_user();
                break;
            case 12:
                printf("请输入要确认收货的订单ID: ");
                scanf("%d", &order_id);
                getchar();  // 消耗换行符
                confirm_receipt(order_id);
                wait_for_user();
                break;
            case 13: check_low_stock(); wait_for_user(); break;
            case 14: process_restock_tasks(); wait_for_user(); break;
            case 15: print_system_status(); wait_for_user(); break;
            case 16: cleanup_old_orders(); wait_for_user(); break;
            case 17: list_products_by_sales(); wait_for_user(); break;  // 新增
            case 18: print_category_stats(); wait_for_user(); break;  // 新增
            case 0: 
                printf("退出系统...\n"); 
                save_data_to_file();
                break;
            default: printf("无效的选择，请重新输入\n");
        }
    } while (choice != 0);
    
    return 0;
}

// 显示菜单
void show_menu() {
    printf("\n===== 电商平台管理系统 =====\n");
    printf("1. 添加商品\n");
    printf("2. 查看所有商品(按名称排序)\n");
    printf("3. 搜索商品\n");
    printf("4. 添加用户\n");
    printf("5. 查看所有用户\n");
    printf("6. 搜索用户\n");
    printf("7. 创建订单\n");
    printf("8. 查看所有订单\n");
    printf("9. 搜索订单\n");
    printf("10. 处理付款\n");
    printf("11. 处理发货\n");
    printf("12. 确认收货\n");
    printf("13. 检查低库存商品\n");
    printf("14. 处理补货任务\n");
    printf("15. 查看系统状态\n");
    printf("16. 清理旧订单\n");
    printf("17. 查看热销商品(按销量排序)\n");  // 新增
    printf("18. 查看商品类别统计\n");  // 新增
    printf("0. 退出系统\n");
    printf("===========================\n");
}

// 等待用户输入，按任意键返回菜单
void wait_for_user() {
    printf("\n按Enter键返回菜单...");
    while (getchar() != '\n'); // 清除输入缓冲区
}

// 初始化系统
void initialize_system() {
    initialize_hash_table();
    build_category_tree();  // 构建类别树
    
    printf("系统初始化完成\n");
    
    // 如果文件没有加载数据，添加一些测试数据
    if (product_count == 0) {
        add_product(101, "智能手机", "电子产品/手机", 4999.0, 50);
        add_product(102, "笔记本电脑", "电子产品/电脑", 7999.0, 30);
        add_product(103, "纯棉T恤", "服装/上衣", 99.0, 100);
    }
    
    if (user_count == 0) {
        add_user(1, "张三", "北京市朝阳区", "13800138000");
        add_user(2, "李四", "上海市浦东新区", "13900139000");
    }
}

// 初始化哈希表
void initialize_hash_table() {
    for (int i = 0; i < 100; i++) {
        user_hash_table[i] = NULL;
    }
    
    // 重新加载用户到哈希表
    for (int i = 0; i < user_count; i++) {
        hash_table_insert(users[i].id, &users[i]);
    }
}

// 添加商品
int add_product(int id, const char *name, const char *category, float price, int stock) {
    if (product_count >= MAX_PRODUCTS) {
        printf("错误: 商品数量已达上限\n");
        return -1;
    }
    
    // 检查ID是否已存在
    if (find_product_by_id(id) != -1) {
        printf("错误: 商品ID %d 已存在\n", id);
        return -1;
    }
    
    Product *new_product = &products[product_count];
    new_product->id = id;
    strcpy(new_product->name, name);
    strcpy(new_product->category, category);
    new_product->price = price;
    new_product->stock = stock;
    new_product->sales = 0;
    
    // 添加到类别树
    CategoryNode *category_node = find_or_create_category_path(category);
    if (category_node) {
        category_node->product_count++;
    }
    
    product_count++;
    return id;
}

// 从键盘输入商品信息
void input_product() {
    int id, stock;
    float price;
    char name[MAX_NAME_LENGTH], category[MAX_CATEGORY_LENGTH];
    
    printf("\n===== 添加商品 =====\n");
    printf("商品ID: ");
    if (scanf("%d", &id) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    printf("商品名称: ");
    fgets(name, MAX_NAME_LENGTH, stdin);
    name[strcspn(name, "\n")] = 0;  // 去除换行符
    
    printf("商品类别(使用'/'分隔层级，如'电子产品/手机'): ");
    fgets(category, MAX_CATEGORY_LENGTH, stdin);
    category[strcspn(category, "\n")] = 0;  // 去除换行符
    
    printf("商品价格: ");
    if (scanf("%f", &price) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    printf("商品库存: ");
    if (scanf("%d", &stock) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    if (add_product(id, name, category, price, stock) != -1) {
        printf("商品添加成功!\n");
    }
}

// 显示所有商品（按名称排序）
void list_products() {
    if (product_count == 0) {
        printf("暂无商品信息\n");
        return;
    }
    
    printf("\n===== 商品列表(按名称排序) =====\n");
    sort_products_by_name();  // 按名称排序
    for (int i = 0; i < product_count; i++) {
        print_product(i);
    }
    printf("===================\n");
}

// 显示所有商品（按销量排序）
void list_products_by_sales() {
    if (product_count == 0) {
        printf("暂无商品信息\n");
        return;
    }
    
    printf("\n===== 热销商品排行(按销量排序) =====\n");
    sort_products_by_sales();  // 按销量排序
    for (int i = 0; i < product_count; i++) {
        if (products[i].sales > 0) {
            print_product(i);
        }
    }
    printf("===================\n");
}

// 搜索商品
void search_product() {
    printf("\n===== 搜索商品 =====\n");
    printf("1. 按ID搜索\n");
    printf("2. 按名称搜索\n");
    printf("3. 按类别搜索\n");
    printf("选择搜索方式: ");
    
    int choice;
    if (scanf("%d", &choice) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    if (choice == 1) {
        int id;
        printf("输入商品ID: ");
        if (scanf("%d", &id) != 1) {
            printf("输入错误，请输入一个数字\n");
            while (getchar() != '\n'); // 清除错误输入
            return;
        }
        getchar();  // 消耗换行符
        
        int index = find_product_by_id(id);
        if (index != -1) {
            print_product(index);
        } else {
            printf("未找到商品ID为 %d 的商品\n", id);
        }
    } else if (choice == 2) {
        char name[MAX_NAME_LENGTH];
        printf("输入商品名称: ");
        fgets(name, MAX_NAME_LENGTH, stdin);
        name[strcspn(name, "\n")] = 0;  // 去除换行符
        
        sort_products_by_name();  // 先排序以便二分查找
        int index = find_product_by_name(name);
        if (index != -1) {
            print_product(index);
        } else {
            printf("未找到名称为 %s 的商品\n", name);
        }
    } else if (choice == 3) {
        char category[MAX_CATEGORY_LENGTH];
        printf("输入商品类别: ");
        fgets(category, MAX_CATEGORY_LENGTH, stdin);
        category[strcspn(category, "\n")] = 0;  // 去除换行符
        
        printf("\n===== 类别 '%s' 的商品 =====\n", category);
        int found = 0;
        for (int i = 0; i < product_count; i++) {
            if (strstr(products[i].category, category) != NULL) {
                print_product(i);
                found = 1;
            }
        }
        if (!found) {
            printf("未找到类别为 %s 的商品\n", category);
        }
    } else {
        printf("无效的选择\n");
    }
}

// 线性查找商品 by ID
int find_product_by_id(int id) {
    for (int i = 0; i < product_count; i++) {
        if (products[i].id == id) {
            return i;
        }
    }
    return -1;
}

// 二分查找商品 by 名称 (需要先排序)
int find_product_by_name(const char *name) {
    int left = 0, right = product_count - 1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        int cmp = strcmp(products[mid].name, name);
        
        if (cmp == 0) {
            return mid;
        } else if (cmp < 0) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1; // 未找到
}

// 使用优化的插入排序对商品按名称排序
void sort_products_by_name() {
    for (int i = 1; i < product_count; i++) {
        Product key = products[i];
        int j = i - 1;
        
        while (j >= 0 && strcmp(products[j].name, key.name) > 0) {
            products[j + 1] = products[j];
            j--;
        }
        
        products[j + 1] = key;
    }
}

// 使用优化的插入排序对商品按销量排序
void sort_products_by_sales() {
    for (int i = 1; i < product_count; i++) {
        Product key = products[i];
        int j = i - 1;
        
        while (j >= 0 && products[j].sales < key.sales) {
            products[j + 1] = products[j];
            j--;
        }
        
        products[j + 1] = key;
    }
}

// 打印商品信息
void print_product(int index) {
    if (index < 0 || index >= product_count) {
        printf("错误: 商品索引无效\n");
        return;
    }
    
    Product *p = &products[index];
    printf("商品ID: %-5d 名称: %-20s 类别: %-15s 价格: %-8.2f 库存: %-5d 销量: %d\n",
           p->id, p->name, p->category, p->price, p->stock, p->sales);
}

// 添加用户
int add_user(int id, const char *name, const char *address, const char *contact) {
    if (user_count >= MAX_USERS) {
        printf("错误: 用户数量已达上限\n");
        return -1;
    }
    
    // 检查ID是否已存在
    if (find_user_by_id(id) != NULL) {
        printf("错误: 用户ID %d 已存在\n", id);
        return -1;
    }
    
    User *new_user = &users[user_count];
    new_user->id = id;
    strcpy(new_user->name, name);
    strcpy(new_user->address, address);
    strcpy(new_user->contact, contact);
    
    // 添加到哈希表
    hash_table_insert(id, new_user);
    
    user_count++;
    return id;
}

// 从键盘输入用户信息
void input_user() {
    int id;
    char name[MAX_NAME_LENGTH], address[MAX_ADDRESS_LENGTH], contact[MAX_NAME_LENGTH];
    
    printf("\n===== 添加用户 =====\n");
    printf("用户ID: ");
    if (scanf("%d", &id) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    printf("用户姓名: ");
    fgets(name, MAX_NAME_LENGTH, stdin);
    name[strcspn(name, "\n")] = 0;  // 去除换行符
    
    printf("用户地址: ");
    fgets(address, MAX_ADDRESS_LENGTH, stdin);
    address[strcspn(address, "\n")] = 0;  // 去除换行符
    
    printf("用户联系方式: ");
    fgets(contact, MAX_NAME_LENGTH, stdin);
    contact[strcspn(contact, "\n")] = 0;  // 去除换行符
    
    if (add_user(id, name, address, contact) != -1) {
        printf("用户添加成功!\n");
    }
}

// 显示所有用户
void list_users() {
    if (user_count == 0) {
        printf("暂无用户信息\n");
        return;
    }
    
    printf("\n===== 用户列表 =====\n");
    for (int i = 0; i < user_count; i++) {
        print_user(i);
    }
    printf("===================\n");
}

// 搜索用户
void search_user() {
    printf("\n===== 搜索用户 =====\n");
    printf("1. 按ID搜索\n");
    printf("2. 按名称搜索\n");
    printf("选择搜索方式: ");
    
    int choice;
    if (scanf("%d", &choice) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    if (choice == 1) {
        int id;
        printf("输入用户ID: ");
        if (scanf("%d", &id) != 1) {
            printf("输入错误，请输入一个数字\n");
            while (getchar() != '\n'); // 清除错误输入
            return;
        }
        getchar();  // 消耗换行符
        
        User *user = find_user_by_id(id);
        if (user != NULL) {
            for (int i = 0; i < user_count; i++) {
                if (&users[i] == user) {
                    print_user(i);
                    break;
                }
            }
        } else {
            printf("未找到用户ID为 %d 的用户\n", id);
        }
    } else if (choice == 2) {
        char name[MAX_NAME_LENGTH];
        printf("输入用户姓名: ");
        fgets(name, MAX_NAME_LENGTH, stdin);
        name[strcspn(name, "\n")] = 0;  // 去除换行符
        
        int index = find_user_by_name(name);
        if (index != -1) {
            print_user(index);
        } else {
            printf("未找到姓名为 %s 的用户\n", name);
        }
    } else {
        printf("无效的选择\n");
    }
}

// 通过ID查找用户 (使用哈希表)
User* find_user_by_id(int id) {
    unsigned int index = hash_function(id);
    
    HashNode *current = user_hash_table[index];
    while (current != NULL) {
        if (current->key == id) {
            return current->user;
        }
        current = current->next;
    }
    
    return NULL; // 未找到
}

// 通过名称查找用户 (线性查找)
int find_user_by_name(const char *name) {
    for (int i = 0; i < user_count; i++) {
        if (strcmp(users[i].name, name) == 0) {
            return i;
        }
    }
    return -1;
}

// 打印用户信息
void print_user(int index) {
    if (index < 0 || index >= user_count) {
        printf("错误: 用户索引无效\n");
        return;
    }
    
    User *u = &users[index];
    printf("用户ID: %-5d 姓名: %-15s 地址: %-30s 联系方式: %s\n",
           u->id, u->name, u->address, u->contact);
}

// 创建订单
int create_order(int user_id, int product_id, int quantity) {
    if (order_count >= MAX_ORDERS) {
        printf("错误: 订单数量已达上限\n");
        return -1;
    }
    
    // 检查用户是否存在
    User *user = find_user_by_id(user_id);
    if (user == NULL) {
        printf("错误: 用户ID %d 不存在\n", user_id);
        return -1;
    }
    
    // 检查商品是否存在
    int product_index = find_product_by_id(product_id);
    if (product_index == -1) {
        printf("错误: 商品ID %d 不存在\n", product_id);
        return -1;
    }
    
    // 检查库存
    if (products[product_index].stock < quantity) {
        printf("错误: 商品库存不足 (现有库存: %d, 需求: %d)\n",
               products[product_index].stock, quantity);
        return -1;
    }
    
    // 创建新订单
    Order *new_order = &orders[order_count];
    new_order->id = order_count + 1;  // 简单自增ID
    new_order->user_id = user_id;
    new_order->product_id = product_id;
    new_order->quantity = quantity;
    new_order->order_time = time(NULL);
    new_order->status = PENDING_PAYMENT;
    
    // 记录订单历史
    push_order_history(new_order->id, new_order->status);
    
    order_count++;
    
    // 更新库存
    update_stock(product_id, -quantity);
    
    printf("订单创建成功: 订单ID=%d\n", new_order->id);
    return new_order->id;
}

// 从键盘输入订单信息
void input_order() {
    int user_id, product_id, quantity;
    
    printf("\n===== 创建订单 =====\n");
    printf("用户ID: ");
    if (scanf("%d", &user_id) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    printf("商品ID: ");
    if (scanf("%d", &product_id) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    printf("购买数量: ");
    if (scanf("%d", &quantity) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    if (create_order(user_id, product_id, quantity) != -1) {
        printf("订单创建成功!\n");
    }
}

// 显示所有订单
void list_orders() {
    if (order_count == 0) {
        printf("暂无订单信息\n");
        return;
    }
    
    printf("\n===== 订单列表 =====\n");
    sort_orders_by_time();  // 按时间排序
    for (int i = 0; i < order_count; i++) {
        print_order(i);
    }
    printf("===================\n");
}

// 搜索订单
void search_order() {
    printf("\n===== 搜索订单 =====\n");
    printf("1. 按订单ID搜索\n");
    printf("2. 按用户ID搜索\n");
    printf("3. 按商品ID搜索\n");
    printf("4. 按状态搜索\n");
    printf("选择搜索方式: ");
    
    int choice;
    if (scanf("%d", &choice) != 1) {
        printf("输入错误，请输入一个数字\n");
        while (getchar() != '\n'); // 清除错误输入
        return;
    }
    getchar();  // 消耗换行符
    
    int id;
    int found = 0;
    char status_input[20];
    
    switch (choice) {
        case 1:
            printf("输入订单ID: ");
            if (scanf("%d", &id) != 1) {
                printf("输入错误，请输入一个数字\n");
                while (getchar() != '\n'); // 清除错误输入
                return;
            }
            getchar();  // 消耗换行符
            
            Order *order = find_order_by_id(id);
            if (order != NULL) {
                for (int i = 0; i < order_count; i++) {
                    if (&orders[i] == order) {
                        print_order(i);
                        found = 1;
                        break;
                    }
                }
            }
            if (!found) {
                printf("未找到订单ID为 %d 的订单\n", id);
            }
            break;
            
        case 2:
            printf("输入用户ID: ");
            if (scanf("%d", &id) != 1) {
                printf("输入错误，请输入一个数字\n");
                while (getchar() != '\n'); // 清除错误输入
                return;
            }
            getchar();  // 消耗换行符
            
            found = 0;
            for (int i = 0; i < order_count; i++) {
                if (orders[i].user_id == id) {
                    print_order(i);
                    found = 1;
                }
            }
            if (!found) {
                printf("未找到用户ID为 %d 的订单\n", id);
            }
            break;
            
        case 3:
            printf("输入商品ID: ");
            if (scanf("%d", &id) != 1) {
                printf("输入错误，请输入一个数字\n");
                while (getchar() != '\n'); // 清除错误输入
                return;
            }
            getchar();  // 消耗换行符
            
            found = 0;
            for (int i = 0; i < order_count; i++) {
                if (orders[i].product_id == id) {
                    print_order(i);
                    found = 1;
                }
            }
            if (!found) {
                printf("未找到商品ID为 %d 的订单\n", id);
            }
            break;
            
        case 4:
            printf("输入订单状态(未付款, 已付款, 已发货, 已完成): ");
            fgets(status_input, 20, stdin);
            status_input[strcspn(status_input, "\n")] = 0;  // 去除换行符
            
            OrderStatus status;
            if (strcmp(status_input, "未付款") == 0) {
                status = PENDING_PAYMENT;
            } else if (strcmp(status_input, "已付款") == 0) {
                status = PAID;
            } else if (strcmp(status_input, "已发货") == 0) {
                status = SHIPPED;
            } else if (strcmp(status_input, "已完成") == 0) {
                status = COMPLETED;
            } else {
                printf("无效的状态输入\n");
                return;
            }
            
            found = 0;
            for (int i = 0; i < order_count; i++) {
                if (orders[i].status == status) {
                    print_order(i);
                    found = 1;
                }
            }
            if (!found) {
                printf("未找到状态为 %s 的订单\n", status_input);
            }
            break;
            
        default:
            printf("无效的选择\n");
    }
}

// 通过ID查找订单
Order* find_order_by_id(int id) {
    for (int i = 0; i < order_count; i++) {
        if (orders[i].id == id) {
            return &orders[i];
        }
    }
    return NULL;
}

// 对订单按下单时间排序
void sort_orders_by_time() {
    for (int i = 1; i < order_count; i++) {
        Order key = orders[i];
        int j = i - 1;
        
        while (j >= 0 && orders[j].order_time > key.order_time) {
            orders[j + 1] = orders[j];
            j--;
        }
        
        orders[j + 1] = key;
    }
}

// 打印订单信息
void print_order(int index) {
    if (index < 0 || index >= order_count) {
        printf("错误: 订单索引无效\n");
        return;
    }
    
    Order *o = &orders[index];
    char *status_str;
    
    switch (o->status) {
        case PENDING_PAYMENT: status_str = "未付款"; break;
        case PAID: status_str = "已付款"; break;
        case SHIPPED: status_str = "已发货"; break;
        case COMPLETED: status_str = "已完成"; break;
        default: status_str = "未知状态";
    }
    
    User *user = find_user_by_id(o->user_id);
    Product *product = &products[find_product_by_id(o->product_id)];
    
    printf("订单ID: %-5d 用户: %-15s 商品: %-20s 数量: %-5d 金额: %-8.2f 下单时间: %-24s 状态: %s\n",
           o->id, 
           user ? user->name : "未知用户",
           product ? product->name : "未知商品",
           o->quantity,
           product ? product->price * o->quantity : 0.0,
           ctime(&o->order_time),
           status_str);
}

// 更新库存
int update_stock(int product_id, int quantity) {
    int index = find_product_by_id(product_id);
    if (index == -1) {
        printf("错误: 商品ID %d 不存在\n", product_id);
        return 0;
    }
    
    // 检查扣减库存是否足够
    if (quantity < 0 && products[index].stock < (-quantity)) {
        printf("错误: 库存不足，无法扣减 %d 个单位\n", -quantity);
        return 0;
    }
    
    products[index].stock += quantity;
    return 1;
}

// 检查低库存商品
void check_low_stock() {
    printf("\n===== 低库存商品检查 =====\n");
    int low_stock_count = 0;
    
    for (int i = 0; i < product_count; i++) {
        if (products[i].stock < RESTOCK_THRESHOLD) {
            printf("警告: 商品 %s (ID:%d) 库存不足，当前库存: %d\n",
                   products[i].name, products[i].id, products[i].stock);
            
            // 确定补货优先级
            int priority;
            if (products[i].stock == 0) {
                priority = 1;  // 缺货，高优先级
            } else if (products[i].stock < RESTOCK_THRESHOLD / 2) {
                priority = 2;  // 库存极低，中优先级
            } else {
                priority = 3;  // 库存低，低优先级
            }
            
            // 添加到补货队列
            enqueue_restock_task(products[i].id, priority);
            low_stock_count++;
        }
    }
    
    if (low_stock_count == 0) {
        printf("所有商品库存充足\n");
    }
    printf("===========================\n");
}

// 处理补货任务
void process_restock_tasks() {
    printf("\n===== 处理补货任务 =====\n");
    if (is_restock_queue_empty()) {
        printf("没有需要处理的补货任务\n");
        return;
    }
    
    while (!is_restock_queue_empty()) {
        RestockTask task = dequeue_restock_task();
        int product_index = find_product_by_id(task.product_id);
        
        if (product_index != -1) {
            // 确定补货数量
            int restock_amount = 100 - products[product_index].stock;  // 补货到100
            if (restock_amount <= 0) restock_amount = 50;  // 至少补货50
            
            // 执行补货
            update_stock(task.product_id, restock_amount);
            
            printf("补货完成: 商品 %s (ID:%d), 补货数量: %d, 新库存: %d, 优先级: %d\n",
                   products[product_index].name, task.product_id,
                   restock_amount, products[product_index].stock, task.priority);
        }
    }
    printf("=========================\n");
}

// 订单历史栈操作 - 压栈
void push_order_history(int order_id, OrderStatus old_status) {
    if (history_count >= MAX_ORDERS) {
        printf("错误: 订单历史记录已满\n");
        return;
    }
    
    OrderHistoryItem item;
    item.order_id = order_id;
    item.old_status = old_status;
    item.timestamp = time(NULL);
    
    order_history[history_count++] = item;
}

// 获取订单历史记录
OrderHistoryItem* get_order_history(int order_id, int *count) {
    static OrderHistoryItem result[MAX_ORDERS];
    int found = 0;
    
    for (int i = 0; i < history_count; i++) {
        if (order_history[i].order_id == order_id) {
            result[found++] = order_history[i];
        }
    }
    
    *count = found;
    return found > 0 ? result : NULL;
}

// 检查订单是否有历史记录
int has_order_history(int order_id) {
    for (int i = 0; i < history_count; i++) {
        if (order_history[i].order_id == order_id) {
            return 1;
        }
    }
    return 0;
}

// 补货任务队列操作 - 入队
void enqueue_restock_task(int product_id, int priority) {
    if (restock_count >= MAX_PRODUCTS) {
        printf("错误: 补货队列已满\n");
        return;
    }
    
    // 检查是否已存在相同商品的补货任务
    for (int i = 0; i < restock_count; i++) {
        if (restock_queue[i].product_id == product_id) {
            // 如果新优先级更高，则更新优先级
            if (priority < restock_queue[i].priority) {
                restock_queue[i].priority = priority;
                restock_queue[i].timestamp = time(NULL);
                printf("更新补货任务: 商品ID %d 优先级提升为 %d\n", product_id, priority);
            }
            return;
        }
    }
    
    // 按优先级插入队列
    int insert_pos = restock_count;
    for (int i = 0; i < restock_count; i++) {
        if (restock_queue[i].priority > priority || 
            (restock_queue[i].priority == priority && 
             restock_queue[i].timestamp > time(NULL))) {
            insert_pos = i;
            break;
        }
    }
    
    // 移动元素为新任务腾出位置
    for (int i = restock_count; i > insert_pos; i--) {
        restock_queue[i] = restock_queue[i - 1];
    }
    
    // 添加新任务
    restock_queue[insert_pos].product_id = product_id;
    restock_queue[insert_pos].priority = priority;
    restock_queue[insert_pos].timestamp = time(NULL);
    restock_count++;
}

// 补货任务队列操作 - 出队
RestockTask dequeue_restock_task() {
    if (restock_count <= 0) {
        printf("错误: 补货队列为空\n");
        RestockTask empty = {0, 0, 0};
        return empty;
    }
    
    // 取出队列头部任务
    RestockTask task = restock_queue[0];
    
    // 移动剩余元素
    for (int i = 0; i < restock_count - 1; i++) {
        restock_queue[i] = restock_queue[i + 1];
    }
    
    restock_count--;
    return task;
}

// 检查补货队列是否为空
int is_restock_queue_empty() {
    return restock_count == 0;
}

// 创建类别节点
CategoryNode* create_category_node(const char *name) {
    CategoryNode *node = (CategoryNode*)malloc(sizeof(CategoryNode));
    if (node == NULL) {
        printf("错误: 内存分配失败\n");
        return NULL;
    }
    
    strcpy(node->name, name);
    node->parent = NULL;
    for (int i = 0; i < MAX_PRODUCTS; i++) {
        node->children[i] = NULL;
    }
    node->child_count = 0;
    node->product_count = 0;
    node->sales_total = 0.0;
    
    return node;
}

// 查找或创建类别路径
CategoryNode* find_or_create_category_path(const char *path) {
    if (category_root == NULL) {
        category_root = create_category_node("所有商品");
    }
    
    char path_copy[MAX_CATEGORY_LENGTH];
    strcpy(path_copy, path);
    
    CategoryNode *current = category_root;
    char *token = strtok(path_copy, "/");
    
    while (token != NULL) {
        int found = 0;
        
        // 去除首尾空格
        char *name = token;
        while (isspace(*name)) name++;
        char *end = name + strlen(name) - 1;
        while (end > name && isspace(*end)) end--;
        *(end + 1) = '\0';
        
        // 在当前节点的子节点中查找
        for (int i = 0; i < current->child_count; i++) {
            if (strcmp(current->children[i]->name, name) == 0) {
                current = current->children[i];
                found = 1;
                break;
            }
        }
        
        // 如果没有找到，创建新节点
        if (!found) {
            CategoryNode *new_node = create_category_node(name);
            if (new_node == NULL) {
                return NULL;
            }
            add_child_category(current, new_node);
            current = new_node;
        }
        
        token = strtok(NULL, "/");
    }
    
    return current;
}

// 构建类别树
void build_category_tree() {
    category_root = create_category_node("所有商品");
    
    for (int i = 0; i < product_count; i++) {
        CategoryNode *node = find_or_create_category_path(products[i].category);
        if (node) {
            node->product_count++;
        }
    }
}

// 打印类别统计
void print_category_stats() {
    if (category_root == NULL) {
        printf("类别树未初始化\n");
        return;
    }
    
    printf("\n===== 商品类别统计 =====\n");
    traverse_category_tree(category_root, 0);
    printf("========================\n");
}

// 添加子类别
void add_child_category(CategoryNode *parent, CategoryNode *child) {
    if (parent == NULL || child == NULL) return;
    
    if (parent->child_count >= MAX_PRODUCTS) {
        printf("错误: 类别子节点数量已达上限\n");
        return;
    }
    
    child->parent = parent;
    parent->children[parent->child_count++] = child;
}

// 遍历类别树 (先序遍历)
void traverse_category_tree(CategoryNode *node, int depth) {
    if (node == NULL) return;
    
    // 打印缩进
    for (int i = 0; i < depth; i++) {
        printf("  ");
    }
    
    // 打印类别信息
    printf("类别: %s, 商品数量: %d, 销售总额: %.2f\n",
           node->name, node->product_count, node->sales_total);
    
    // 递归遍历子类别
    for (int i = 0; i < node->child_count; i++) {
        traverse_category_tree(node->children[i], depth + 1);
    }
}

// 更新类别统计信息
void update_category_stats(Product *product, float sales_amount) {
    if (product == NULL) return;
    
    // 查找商品对应的类别节点
    CategoryNode *node = find_or_create_category_path(product->category);
    if (node == NULL) return;
    
    // 更新从当前节点到根节点的所有节点
    CategoryNode *current = node;
    while (current != NULL) {
        current->sales_total += sales_amount;
        current = current->parent;
    }
}

// 哈希函数
unsigned int hash_function(int key) {
    return key % 100;
}

// 哈希表插入
void hash_table_insert(int key, User *user) {
    unsigned int index = hash_function(key);
    
    // 创建新节点
    HashNode *new_node = (HashNode*)malloc(sizeof(HashNode));
    if (new_node == NULL) {
        printf("错误: 内存分配失败\n");
        return;
    }
    
    new_node->key = key;
    new_node->user = user;
    new_node->next = user_hash_table[index];
    
    // 插入到链表头部
    user_hash_table[index] = new_node;
}

// 哈希表查找
User* hash_table_lookup(int key) {
    unsigned int index = hash_function(key);
    
    // 遍历链表
    HashNode *current = user_hash_table[index];
    while (current != NULL) {
        if (current->key == key) {
            return current->user;
        }
        current = current->next;
    }
    
    return NULL; // 未找到
}

// 打印系统状态
void print_system_status() {
    printf("\n===== 系统状态总结 =====\n");
    
    printf("\n商品总数: %d\n", product_count);
    sort_products_by_name();  // 按名称排序
    for (int i = 0; i < product_count; i++) {
        print_product(i);
    }
    
    printf("\n用户总数: %d\n", user_count);
    for (int i = 0; i < user_count; i++) {
        print_user(i);
    }
    
    printf("\n订单总数: %d\n", order_count);
    sort_orders_by_time();  // 按时间排序
    for (int i = 0; i < order_count; i++) {
        print_order(i);
    }
    
    printf("\n补货队列任务数: %d\n", restock_count);
    for (int i = 0; i < restock_count; i++) {
        printf("优先级: %d, 商品ID: %d, 添加时间: %s",
               restock_queue[i].priority, restock_queue[i].product_id,
               ctime(&restock_queue[i].timestamp));
    }
    
    printf("\n订单历史记录数: %d\n", history_count);
    for (int i = 0; i < history_count; i++) {
        char *status_str;
        switch (order_history[i].old_status) {
            case PENDING_PAYMENT: status_str = "未付款"; break;
            case PAID: status_str = "已付款"; break;
            case SHIPPED: status_str = "已发货"; break;
            case COMPLETED: status_str = "已完成"; break;
            default: status_str = "未知状态";
        }
        
        printf("订单ID: %d, 旧状态: %s, 时间: %s",
               order_history[i].order_id, status_str,
               ctime(&order_history[i].timestamp));
    }
    
    printf("\n===== 系统状态结束 =====\n");
}

// 清理旧订单
void cleanup_old_orders() {
    time_t current_time = time(NULL);
    int deleted_count = 0;
    
    printf("\n===== 清理旧订单 =====\n");
    
    // 标记需要删除的订单
    int to_delete[MAX_ORDERS] = {0};
    for (int i = 0; i < order_count; i++) {
        if (orders[i].status == COMPLETED) {
            // 计算订单完成时间与当前时间的差值
            double diff = difftime(current_time, orders[i].order_time);
            int days = (int)(diff / (60 * 60 * 24));
            
            if (days >= CLEANUP_DAYS) {
                to_delete[i] = 1;
                deleted_count++;
            }
        }
    }
    
    // 如果有需要删除的订单，重新整理数组
    if (deleted_count > 0) {
        int new_count = 0;
        Order temp[MAX_ORDERS];
        
        for (int i = 0; i < order_count; i++) {
            if (!to_delete[i]) {
                temp[new_count++] = orders[i];
            }
        }
        
        // 复制回原数组
        for (int i = 0; i < new_count; i++) {
            orders[i] = temp[i];
        }
        
        order_count = new_count;
        printf("已清理 %d 个超过 %d 天的已完成订单\n", deleted_count, CLEANUP_DAYS);
    } else {
        printf("没有需要清理的订单\n");
    }
    printf("=====================\n");
}

// 处理付款
int process_payment(int order_id) {
    Order *order = find_order_by_id(order_id);
    if (order == NULL) {
        printf("错误: 订单ID %d 不存在\n", order_id);
        return 0;
    }
    
    if (order->status != PENDING_PAYMENT) {
        printf("错误: 订单状态不是未付款状态，当前状态: ");
        switch (order->status) {
            case PAID: printf("已付款\n"); break;
            case SHIPPED: printf("已发货\n"); break;
            case COMPLETED: printf("已完成\n"); break;
            default: printf("未知状态\n");
        }
        return 0;
    }
    
    // 记录历史
    push_order_history(order_id, order->status);
    
    // 更新状态
    order->status = PAID;
    update_stock(order->product_id, -order->quantity);
    
    printf("订单 %d 付款处理成功，当前状态: 已付款\n", order_id);
    return 1;
}

// 处理发货
int process_shipment(int order_id) {
    Order *order = find_order_by_id(order_id);
    if (order == NULL) {
        printf("错误: 订单ID %d 不存在\n", order_id);
        return 0;
    }
    
    if (order->status != PAID) {
        printf("错误: 订单状态不是已付款状态，当前状态: ");
        switch (order->status) {
            case PENDING_PAYMENT: printf("未付款\n"); break;
            case SHIPPED: printf("已发货\n"); break;
            case COMPLETED: printf("已完成\n"); break;
            default: printf("未知状态\n");
        }
        return 0;
    }
    
    // 记录历史
    push_order_history(order_id, order->status);
    
    // 更新状态
    order->status = SHIPPED;
    
    printf("订单 %d 发货处理成功，当前状态: 已发货\n", order_id);
    return 1;
}

// 确认收货
int confirm_receipt(int order_id) {
    Order *order = find_order_by_id(order_id);
    if (order == NULL) {
        printf("错误: 订单ID %d 不存在\n", order_id);
        return 0;
    }
    
    if (order->status != SHIPPED) {
        printf("错误: 订单状态不是已发货状态，当前状态: ");
        switch (order->status) {
            case PENDING_PAYMENT: printf("未付款\n"); break;
            case PAID: printf("已付款\n"); break;
            case COMPLETED: printf("已完成\n"); break;
            default: printf("未知状态\n");
        }
        return 0;
    }
    
    // 记录历史
    push_order_history(order_id, order->status);
    
    // 更新状态
    order->status = COMPLETED;
    
    // 更新商品销量
    int product_index = find_product_by_id(order->product_id);
    if (product_index != -1) {
        products[product_index].sales += order->quantity;
        
        // 更新类别统计
        float sales_amount = products[product_index].price * order->quantity;
        update_category_stats(&products[product_index], sales_amount);
    }
    
    printf("订单 %d 收货确认成功，当前状态: 已完成\n", order_id);
    return 1;
}

// 保存数据到文件
void save_data_to_file() {
    FILE *file = fopen(DATA_FILE, "wb");
    if (file == NULL) {
        printf("无法打开文件进行写入\n");
        return;
    }
    
    // 保存商品数据
    fwrite(&product_count, sizeof(int), 1, file);
    fwrite(products, sizeof(Product), product_count, file);
    
    // 保存用户数据
    fwrite(&user_count, sizeof(int), 1, file);
    fwrite(users, sizeof(User), user_count, file);
    
    // 保存订单数据
    fwrite(&order_count, sizeof(int), 1, file);
    fwrite(orders, sizeof(Order), order_count, file);
    
    fclose(file);
    printf("数据已保存到文件\n");
}

// 从文件加载数据
void load_products() {
    FILE *fp = fopen(PRODUCTS_PATH, "r");
    if (!fp) {
        printf("无法打开产品数据文件\n");
        return;
    }

    char line[256];
    while (fgets(line, sizeof(line), fp)) {
        int id, stock, sales;
        char name[MAX_NAME_LENGTH], category[MAX_CATEGORY_LENGTH];
        float price;
        
        if (sscanf(line, "%d,%[^,],%[^,],%f,%d,%d",
                 &id, name, category, &price, &stock, &sales) == 6) {
            if (product_count < MAX_PRODUCTS) {
                Product *p = &products[product_count++];
                p->id = id;
                strcpy(p->name, name);
                strcpy(p->category, category);
                p->price = price;
                p->stock = stock;
                p->sales = sales;
            }
        }
    }
    fclose(fp);
    printf("产品数据加载完成\n");
}

